package com.lzc.tlmail.cart.tlmailcart.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lzc.common.utils.R;
import com.lzc.tlmail.cart.tlmailcart.feign.ProductFeignService;
import com.lzc.tlmail.cart.tlmailcart.interceptor.CartInterceptor;
import com.lzc.tlmail.cart.tlmailcart.service.CartService;
import com.lzc.tlmail.cart.tlmailcart.to.UserInfoto;
import com.lzc.tlmail.cart.tlmailcart.vo.CartItemVo;
import com.lzc.tlmail.cart.tlmailcart.vo.CartVo;
import com.lzc.tlmail.cart.tlmailcart.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.lzc.common.constant.CartConstant.CART_PREFIX;

/**
 * @author lzc
 * @create 2020-10-19 10:29
 */
@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 添加购物车
     * @param skuNum
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo addCart(Integer skuNum, Long skuId) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        //判断商品已近添加到redis里面去了没有 有了就只需要修改数量就好了否则才添加
        String o = (String) operations.get(skuId.toString());
        if(StringUtils.isEmpty(o)){
            R skuInfo = productFeignService.getSkuInfo(skuId);
            CartItemVo cartItemVo = new CartItemVo();
            if(skuInfo.getCode()==0){

                CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> {
                    //得到sku信息设置到购物车项
                    SkuInfoVo skuInfoData = skuInfo.getData("data", new TypeReference<SkuInfoVo>() {
                    });
                    cartItemVo.setChecked(true);
                    cartItemVo.setCount(skuNum);
                    cartItemVo.setSkuId(skuId);
                    cartItemVo.setDefaultIamge(skuInfoData.getSkuDefaultImg());
                    cartItemVo.setPrice(skuInfoData.getPrice());
                    cartItemVo.setSkuTitle(skuInfoData.getSkuTitle());
                }, executor);
                CompletableFuture<Void> runAsync1 = CompletableFuture.runAsync(() -> {
                    //得到sku属性
                    List<String> skuSaleInfo = productFeignService.getSkuSaleInfo(skuId);
                    cartItemVo.setAttrs(skuSaleInfo);
                }, executor);
                CompletableFuture.allOf(runAsync,runAsync1).get();

                String s = JSON.toJSONString(cartItemVo);
                operations.put(skuId.toString(),s);

                return cartItemVo;
            }else {
                return null;
            }
        }else {
            CartItemVo cartItemVo1 = JSON.parseObject(o, CartItemVo.class);
            cartItemVo1.setCount(cartItemVo1.getCount()+skuNum);
            String s = JSON.toJSONString(cartItemVo1);
            operations.put(skuId.toString(),s);
            return cartItemVo1;
        }




    }

    /**
     * 根据skuid得到购物车项
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItemBySkuId(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        String o = (String) operations.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
        return cartItemVo;
    }

    /**
     * 获取购物车内容
     * @return
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        //先判断是登陆还是不登陆
        UserInfoto userInfoto = CartInterceptor.userInfotoThreadLocal.get();
        CartVo cartVo = new CartVo();
        String userKey = CART_PREFIX + userInfoto.getUserKey();
        String loginKey = CART_PREFIX + userInfoto.getUserId();
        if(userInfoto.getUserId()!=null){

            //登陆的就要把自己的购物车内容和临时的内容合并起来

            //在获取临时的合并起来
            List<CartItemVo> cartItems = getCartItems(userKey);
            if(cartItems!=null&&cartItems.size()>0){
                for (CartItemVo item : cartItems) {
                    addCart(item.getCount(),item.getSkuId());
                }
                clearCart(userKey);
            }
            //登陆了获取登录的
            List<CartItemVo> cartItemVos = getCartItems(loginKey);
            cartVo.setCartItemVoList(cartItemVos);
            return cartVo;
        }else {
            //没登录的就获取临时购物车内容
            List<CartItemVo> cartItems = getCartItems(userKey);
            cartVo.setCartItemVoList(cartItems);
            return cartVo;
        }
    }
    @Override
    public  List<CartItemVo> getCartItems(String userKey) {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(userKey);
        List<Object> values = operations.values();
        if(values!=null&&values.size()>0){
            List<CartItemVo> cartItemVos = values.stream().map(obj -> {
                String cartItem = (String) obj;
                CartItemVo cartItemVo = JSON.parseObject(cartItem, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return cartItemVos;
        }else {
            return null;
        }
    }

    /**
     * 清空临时购物车
     * @param key
     */
    @Override
    public void clearCart(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 修改选中商品项状态
     * @param checked
     * @param skuId
     */
    @Override
    public void cartCheck(Integer checked, Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        CartItemVo item = getCartItemBySkuId(skuId);
        item.setChecked(checked==1?true:false);
        String s = JSON.toJSONString(item);
        operations.put(skuId.toString(),s);
    }

    /**
     * 修改商品增减数量
     * @param count
     * @param skuId
     */
    @Override
    public void cartNumChange(Integer count, Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        CartItemVo item = getCartItemBySkuId(skuId);
        item.setCount(count);
        String s = JSON.toJSONString(item);
        operations.put(skuId.toString(),s);
    }

    /**
     * 删除购物车
     * @param skuId
     */
    @Override
    public void skuDel(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        operations.delete(skuId.toString());
    }

    /**
     * 获取购物项到订单显示(选中的购物项)
     * @return
     */
    @Override
    public List<CartItemVo> getCartItemsToOrder() {
        UserInfoto userInfoto = CartInterceptor.userInfotoThreadLocal.get();
        if(userInfoto.getUserId()!=null){
            String s = CART_PREFIX + userInfoto.getUserId();
            List<CartItemVo> cartItems = getCartItems(s);
            List<CartItemVo> cartItemVos = cartItems.stream().filter(item -> item.getChecked()).map(item->{
                BigDecimal skuPrice = productFeignService.getSkuPrice(item.getSkuId());
                item.setPrice(skuPrice);
                return item;
            }).collect(Collectors.toList());
            return cartItemVos;
        }else {

            return null;
        }

    }

    private BoundHashOperations<String, Object, Object>  getOperations() {
        UserInfoto userInfoto = CartInterceptor.userInfotoThreadLocal.get();
        String cartKey="";
        if(userInfoto.getUserId()!=null){
            cartKey=CART_PREFIX+userInfoto.getUserId();
        }else{
            cartKey=CART_PREFIX+userInfoto.getUserKey();
        }
         return redisTemplate.boundHashOps(cartKey);
    }
}
